<template>
  <el-header height="48px" class="header">
    <!-- 添加移动端菜单按钮 -->
    <div class="header-left">
      <el-icon v-if="isMobile" class="toggle-btn" @click="toggleAside">
        <component :is="isCollapse ? 'Expand' : 'Fold'" />
      </el-icon>
      <!-- 单位选择器 -->
      <div class="company-selector-container">
        <SvgIcon size="20px" icon="company" />
        <div v-if="userStore.role === 'admin'" class="company-selector">
          <CompanyAutoInput size="small" v-model="currentCompany" />
        </div>
        <div v-else>
          {{ currentCompany.name }}
        </div>
      </div>
    </div>

    <div class="header-right">
      <el-space>
        <el-dropdown @command="handleCommand">
          <div ref="trigger" class="user-info">
            <span class="username">{{ userInfo.real_name }}</span>
            <el-icon class="dropdown-icon">
              <CaretBottom />
            </el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="userInfo">
                <el-icon>
                  <User />
                </el-icon>个人信息
              </el-dropdown-item>
              <el-dropdown-item ref="changePassword" command="changePassword">
                <el-icon>
                  <Lock />
                </el-icon>修改密码
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon>
                  <SwitchButton />
                </el-icon>退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-space>
    </div>

    <el-tour type="primary" :mask="false" v-model="open">
      <el-tour-step :target="trigger" title="修改密码" description="检测到您还未修改密码，请点击修改密码按钮进行密码修改" placement="top-start" />
    </el-tour>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px" @close="resetPasswordForm">
      <el-form v-loading="passwordLoading" ref="passwordFormRef" :model="passwordForm" :rules="passwordRules"
        label-width="100px">
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入旧密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-header>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userinfo'
import { useCompanyStore } from '@/stores/company'
import { useAreaStore } from '@/stores/area'
import { useMeterStore } from '@/stores/meter'
import CompanyAutoInput from '@/views/SystemManagement/CompanyManagement/CompanyList/components/CompanyAutoInput.vue'
import { logoutApi } from '@/api/auth'
import { changePasswordApi } from '@/api/user'
import { sha256 } from '@/utils/sha256'
import SvgIcon from '../icon/SvgIcon.vue'
const trigger = ref(null)
const changePassword = ref(null)
const open = ref(false)
setTimeout(() => {
  const isDefaultPassword = localStorage.getItem('isDefaultPassword')
  if (isDefaultPassword === 'true') {
    open.value = true
  } else {
    open.value = false
  }
  localStorage.removeItem('isDefaultPassword')
}, 1000);
let passwordLoading = ref(false)
// Props 定义
const props = defineProps({
  isCollapse: {
    type: Boolean,
    required: true
  },
  isMobile: {
    type: Boolean,
    required: true
  }
})

// Emits 定义
const emit = defineEmits(['update:isCollapse', 'fullscreenChange'])

// Store 初始化
const userStore = useUserStore()
const companyStore = useCompanyStore()
const areaStore = useAreaStore()
const meterStore = useMeterStore()

// Router 相关
const router = useRouter()

// 响应式状态
const currentCompany = ref(companyStore.currentCompany)
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = ref({
  old_password: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const passwordRules = {
  old_password: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

watch(currentCompany, async (newVal, oldVal) => {
  if (newVal !== oldVal) {
    await handleCompanyChange(newVal)
  }
})

// 计算属性
const userInfo = computed(() => userStore.userinfo || {})

// 方法定义
const toggleAside = () => {
  emit('update:isCollapse', !props.isCollapse)
}

const handleCompanyChange = async (company) => {
  if (!company) return

  try {
    companyStore.setCurrentCompany(company)
    await Promise.all([
      areaStore.fetchAreas(),
      meterStore.fetchMeterList()
    ])
    ElMessage.success('单位切换成功')
  } catch (error) {
    ElMessage.error('数据加载失败，请重试')
  }
}

const handleCommand = async (command) => {
  switch (command) {
    case 'userInfo':
      router.push('/user-info')
      break
    case 'changePassword':
      passwordDialogVisible.value = true
      break
    case 'logout':
      await handleLogout()
      break
  }
}

const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordForm.value = {
    old_password: '',
    newPassword: '',
    confirmPassword: '',
  }
}

const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    passwordLoading.value = true
    await passwordFormRef.value.validate()

    await changePasswordApi({
      username: userInfo.value.username,
      id: userInfo.value.id,
      old_password: sha256(passwordForm.value.old_password),
      password: sha256(passwordForm.value.newPassword),
    })

    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    resetPasswordForm()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('密码修改失败，请重试')
    }
  } finally {
    passwordLoading.value = false
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确认退出登录吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    localStorage.removeItem('permissions')
    router.push('/login')
    ElMessage.success('已安全退出登录')
    await logoutApi()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
    }
  }
}
</script>

<style scoped lang="scss">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1rem;
  background-color: var(--color-background);

  .company-selector-container {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 20px;
    font-weight: 800;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 1rem;

    .toggle-btn {
      font-size: 1.25rem;
      cursor: pointer;
      color: var(--el-text-color-regular);
      transition: color 0.3s;
      padding: 0.5rem;
      border-radius: 4px;
    }
  }

  .header-right {
    margin-left: auto;
    display: flex;
    align-items: center;

    .action-icon {
      font-size: 1.25rem;
      cursor: pointer;
      color: var(--el-text-color-regular);
      transition: color 0.3s;

      &:hover {
        color: var(--el-color-primary);
      }
    }

    .company-selector {
      margin-right: 1rem;
      max-width: 150px;
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      cursor: pointer;
      padding: 0.25rem 0.5rem;
      border-radius: 10px;

      .username {
        font-size: 0.875rem;
        color: var(--el-text-color-regular);
      }

      .dropdown-icon {
        font-size: 0.75rem;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

// 响应式样式
@media screen and (max-width: 768px) {
  .header {
    padding: 0 0.5rem;

    .header-left {
      .toggle-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
      }
    }

    .header-right {
      .company-selector {
        width: 120px;
      }

      .user-info {
        padding: 0.25rem;
      }
    }
  }
}
</style>